<?php
/*
 * 申城Sql代码, 简单的
 * @package    system
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 06467557a34a0f51222e31b42a734dd3352c58e8 $
 */
defined('IN_IXDCW') or exit('Access Denied');
class Sql{

	/**
	 * 插入数据的生成
	 * @param       $table
	 * @param       $info
	 * @param array $fields
	 * @return string
	 */
	public static function insert($table, $info, $fields = array()) {
		$sqlk = $sqlv = '';
		foreach ($info as $k => $v) {

			if (empty($fields)) {

				$sqlk .= ',' . $k;
				$sqlv .= ",'$v'";
			} else if (in_array($k, $fields)) {

				$sqlk .= ',' . $k;
				$sqlv .= ",'$v'";

			}
		}

		$sqlk = substr($sqlk, 1);
		$sqlv = substr($sqlv, 1);

		$sql  = "INSERT INTO {$table} ($sqlk) VALUES ($sqlv)";

       // var_dump($sql);exit;
		return $sql;

	}

	/**
	 * 生成 replace into 语句
	 * @param       $table
	 * @param       $info
	 * @param array $fields
	 * @return string
	 */
	public static function replaceInto($table, $info, $fields = array()) {
		$sqlk = $sqlv = '';
		foreach ($info as $k => $v) {
			if (empty($fields)) {
				$sqlk .= ',' . $k;
				$sqlv .= ",'$v'";
			} else if (in_array($k, $fields)) {
				$sqlk .= ',' . $k;
				$sqlv .= ",'$v'";
			}
		}
		$sqlk = substr($sqlk, 1);
		$sqlv = substr($sqlv, 1);
		$sql  = "REPLACE INTO {$table} ($sqlk) VALUES ($sqlv)";
		return $sql;
	}

	/**
	 * 更新语句
	 * @param       $table
	 * @param       $update
	 * @param       $where
	 * @param array $oldInfo
	 * @param array $fields
	 * @return bool|string
	 */
	public static function update($table, $update, $where, $oldInfo = array(), $fields = array()) {
		$sql = '';
		if (is_array($update)) {
			foreach ($update as $k => $v) {
				// 过滤相同变量
				if ($oldInfo && $update[$k] == $oldInfo[$k]) {
					continue;
				}
				if (empty($fields)) {
					$sql .= ",$k='$v'";
				} else if (in_array($k, $fields)) {
					$sql .= ",$k='$v'";
				}
			}
			$sql = substr($sql, 1);
		} else {
			$sql = $update;
		}
		if ($sql) {
			$sql = "UPDATE {$table} SET {$sql} WHERE {$where}";
			return $sql;
		} else {
			return false; //完全没有修改任何数据
		}
	}

	/**
	 * 删除信息条目
	 * @param $table
	 * @param $where
	 * @return string
	 */
	public static function delete($table, $where) {
		return "Delete FROM {$table} Where {$where}";
	}

	/**
	 * 生成简单的 in 语句
	 * @param $items
	 * @return string
	 */
	public static function in($items){
		return "'".implode('\',\'', $items)."'";
	}
}